// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
exports.main = async (event, context) => {
  //这里只取notpay的订单，init状态的订单表示未成功下单，所以不用处理init的订单
  let notPayOrderResult = await cloud.callFunction({
    name: 'db_Order',
    data: {
      type: 'queryNotPayOrderAll'
    }
  })
  try {
    var notPayOrderArray = notPayOrderResult.result.data
    const nowTime = Date.now()
    const length = notPayOrderArray.length
    for (let index = 0; index < length; index++) {
      const element = notPayOrderArray[index];
      const queryOrderRes = await cloud.callFunction({
        name: 'server_Order',
        data: {
          type: 'queryOrder',
          outTradeNo: element.outTradeNo
        }
      })
      if ("NOTPAY" == queryOrderRes.result.tradeState && (nowTime - element.createTime) >= 1800000) {
        cloud.callFunction({
          name: 'server_Order',
          data: {
            type: 'closeOrder',
            outTradeNo: element.outTradeNo
          }
        })
      }
    }
    return {
      errCode: 0,
      errMsg: 'success',
      arrayLength: length
      //processData: notPayOrderResult
    }
  } catch (error) {
    return {
      errCode: -1,
      errMsg: error,
      arrayLength: length
      //processData: notPayOrderResult
    }
  }
}